/* eslint-disable no-undef */
import { getFile, GET_FILE_URL } from '@/api/file';
import getConfig from '@/server/getConfig';
import axios from 'axios';
import { getFileList, uploadFileMulti } from '@/api/formview';

// todo 请求文件列表
/*
  data: {
    type: string;
    appId: string;
  }
*/

const conversionBase64 = (blob) => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  return new Promise(resolve => {
    reader.onload = ({ target: { result }}) => {
      resolve(result);
    };
  });
};

const saveFileToLocal = (blob, fileName) => {
  const a = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  const filename = fileName;
  a.href = url;
  a.download = filename;
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove();
};

// todo 下载文件
/*
  data: {
    id: string
    fileName: string
    originName: string
  }

  type: string // pic | file ;   //type === pic 返回base64 否则直接下载打开
*/
const downFile = async(data, type) => {
  const { data: blob } = await getFile({
    id: data.id,
    fileName: data.saveName
  });
  if (type === 'pic') {
    return await conversionBase64(blob);
  } else {
    saveFileToLocal(blob, data.saveName);
  }
};

const fileView = async function fileView(id) {
  const { data: { ApiUrl }} = await getConfig();
  const fileViewUrl = `${
    ApiUrl
  }onlinePreview?fileId=${id}`;

  window.open(fileViewUrl);
};

const downFileServer = url => {
  return axios.get(url, {
    responseType: 'blob'
  });
};

// b64转文件
const dataURLtoFile = function(dataUrl, filename) {
  const arr = dataUrl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
};

const getListFiles = function(data, headers = {}) {
  return getFileList(data, headers);
};

const upFileMulti = function(data) {
  return uploadFileMulti(data);
};

// 选择图片
const chooseImgs = function() {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 9,
      success: (res) => {
        resolve({
          paths: res.tempFilePaths,
          files: res.tempFiles
        });
      },

      fail: () => {
        reject('调用图片失败');
      }
    });
  });
};

const getImgUrl = async function({ id, fileName }) {
  const { data: { ApiUrl }} = await getConfig();
  return ApiUrl + 'file/downloadById' + `?id=${id}&fileName=${fileName}`;
};

// 选择附件 // ?选择图片的api不是有了吗
const chooseFile = function() {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      success: (res) => {
        resolve({
          paths: res.tempFilePaths,
          files: res.tempFiles
        });
      },

      fail: () => {
        reject('上传附件失败');
      }
    });
  });
};

const chooseFileUni = function() {
  return new Promise((r, j) => {
    uni.chooseFile({
      extension: ['.doc', '.xlsx', '.docx'],
      success: ({ tempFiles }) => {
        r(tempFiles);
      },

      fail: err => {
        j(err);
      }
    });
  });
};

export {
  downFile,
  fileView,
  downFileServer,
  dataURLtoFile,
  getListFiles,
  upFileMulti,
  chooseImgs,
  chooseFile,
  chooseFileUni,
  getImgUrl,
  conversionBase64,
  GET_FILE_URL
};
